/*
ajax 请求函数模块
返回值：promise 对象（异步返回的是 response.data）
*/
import axios from "axios";

var cancelAxiosList = [];
export { cancelAxiosList };
export default function ajax(url, data = {}, type = "GET") {
  let axiosInstance = axios.create({
    // baseURL: process.env.API_ROOT_ATM,
    // cancelToken : new axios.CancelToken(function executor(cancel) {
    cancelToken: new axios.CancelToken(cancel => {
      cancelAxiosList.push({
        cancel
      });
    })
  });

  return new Promise(function(resolve, reject) {
    // 执行异步 ajax 请求
    let promise;
    if (type === "GET") {
      // 拼接 url
      let dataStr = "";
      Object.keys(data).forEach(key => {
        dataStr += key + "=" + data[key] + "&";
      });
      if (dataStr !== "") {
        dataStr = dataStr.substring(0, dataStr.lastIndexOf("&"));
        url = url + "?" + dataStr;
      }

      promise = axiosInstance.get(url);
    } else {
      promise = axiosInstance.post(url, data);
    }

    promise
      .then(function(response) {
        // 成功了调用 resolve()
        resolve(response.data);
      })
      .catch(function(error) {
        // 失败了调用 reject()
        reject(error);
      });
  });
}
